import os
import tempfile
import requests
from fastapi import FastAPI, Query
from pdf2image import convert_from_path
from paddleocr import PaddleOCR

app = FastAPI()

# 初始化 PaddleOCR
ocr = PaddleOCR(
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
    use_textline_orientation=False
)

@app.get("/ocr/310")
def recognize_pdf(url: str = Query(..., description="Public PDF URL")):
    try:
        # 1. 下载 PDF 文件到临时
        response = requests.get(url)
        response.raise_for_status()
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
            tmp_pdf.write(response.content)
            pdf_path = tmp_pdf.name

        # 2. PDF转图片（每页一张）
        images = convert_from_path(pdf_path)

        results = []
        for img in images:
            # 3. 保存临时图片
            with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_img:
                img.save(tmp_img.name)
                img_path = tmp_img.name

            # 4. OCR识别，调用 predict() 返回 OCRResult 列表
            ocr_results = ocr.predict(img_path)

            # 5. 从 OCRResult 提取 rec_texts
            page_texts = []
            for res in ocr_results:
                # res 是 dict-like，需用 [] 访问
                texts = res.get('rec_texts', [])
                page_texts.extend(texts)

            # 6. 拼接页文本
            page_text = "".join(page_texts)
            results.append(page_text)

            # 7. 清理临时图片
            os.remove(img_path)

        # 清理临时PDF
        os.remove(pdf_path)

        return {"status": "success", "pages": len(results), "content": results}

    except Exception as e:
        print(f"Error processing PDF: {e}")
        return {"status": "error", "message": str(e)}